import React, { Component } from 'react'
import styles from './index.module.scss'
import { Form, Input, Button, message } from 'antd'
import { SHA256 } from 'utils/SHA256.js'
import { login } from 'api/user'
import { setToken } from 'utils/storage'
import {
  TranslationOutlined,
  UserOutlined,
  LockOutlined,
} from '@ant-design/icons'

export default class Login extends Component {
  onFinish = async (values) => {
    const data = { ...values }
    data.password = SHA256(data.password)
    const { state } = this.props.location
    try {
      const res = await login(data)
      setToken(res.token)
      if (state && state.pathname) {
        this.props.history.push(state.pathname)
      } else {
        this.props.history.push('/dashboard')
      }
      message.success('登陆成功')
    } catch (err) {
      message.error(err.message)
    }
  }

  render() {
    return (
      <div className={styles.login}>
        <div className="loginContainer">
          <div className="loginBox">
            <div className="title">
              <div className="left">
                <img src="../../assets/logo.png" alt="" />
                <span>用户登录</span>
              </div>
              <TranslationOutlined style={{ fontSize: 20 }} />
            </div>
            <Form
              name="horizontal_login"
              size="large"
              initialValues={{
                username: 'root@admin.com',
                password: '123456',
              }}
              onFinish={this.onFinish}
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: 'Please input your username!' },
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="Username"
                />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: 'Please input your password!' },
                ]}
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="Password"
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" block htmlType="submit">
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}
